import { ref, computed, onUnmounted } from "vue";

export default function useCountdown(targetTimestamp) {
  const now = ref(Date.now());

  // Update current time every second
  const interval = setInterval(() => {
    now.value = Date.now();
  }, 1000);

  // Cleanup interval on unmount
  onUnmounted(() => {
    clearInterval(interval);
  });

  const remainingTime = computed(() => {
    const diff = targetTimestamp - now.value;

    // Calculate time components
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((diff % (1000 * 60)) / 1000);
    if (diff <= 0) {
      clearInterval(interval);
      return {
        days: "00",
        hours: "00",
        minutes: "00",
        seconds: "00",
        isFinished: true,
      };
    } else {
      return {
        days: days < 10 ? "0" + days : days,
        hours: hours < 10 ? "0" + hours : hours,
        minutes: minutes < 10 ? "0" + minutes : minutes,
        seconds: seconds < 10 ? "0" + seconds : seconds,
        isFinished: diff <= 0,
      };
    }
  });

  return {
    remainingTime,
  };
}
